import { _decorator, Node, Vec3, PhysicsSystem2D, ERaycast2DType, Vec2 } from 'cc';
import { Actor } from '../Actor';
import { delay } from '../../Util/AsyncUtils';
import { Physicsgroup } from '../Config';
import { Player } from '../Player/Player';
import { PlayerManager } from '../Player/PlayerManager';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Actor {

    @property(Vec2) stunDirection: Vec2 = null;
    @property stunDuration: number = 100;

    @property(Node) counterImage: Node = null;
    canBeStunned: boolean = false;

    playerNode: Node = null;

    private defaultMoveSpeed: number;
    start() {
        super.start();
        this.defaultMoveSpeed = this.MoveSpeed;
        this.playerNode = PlayerManager.inst.player.node;
    }

    update(deltaTime: number) {
        this.stateMgr.update(deltaTime);
    }
    public OpenCounterAttackWindow() {
        this.canBeStunned = true;
        this.counterImage.active = true;
    }
    public CloseCounterAttackWindow() {
        this.canBeStunned = false;
        this.counterImage.active = false;
    }
    public CanBeStunned() {//弹反
        if (this.canBeStunned) {
            this.CloseCounterAttackWindow();
            return true;
        }
        return false;
    }
    private FreezeTime(_timeFreeze: boolean): void {
        if (_timeFreeze) {
            this.MoveSpeed = 0;
            this.animation.pause();
        } else {
            this.animation.resume();
            this.MoveSpeed = this.defaultMoveSpeed;
        }
    }
    public async FreezeTimeFor(time: number) {
        this.FreezeTime(true);
        await delay(time);
        this.FreezeTime(false);
    }
    public IsPlayerDetected(): boolean {
        const start = this.wallCheck.getWorldPosition();
        const end = start.clone().add(this.wallCheckDistance.clone().multiply(new Vec3(15, 0, 0)));
        let results = PhysicsSystem2D.instance.raycast(start, end, ERaycast2DType.Any, Physicsgroup.Player);
        return results.length > 0;
    }
    public IsAttackDetected(): boolean {
        const start = this.wallCheck.getWorldPosition();
        const end = start.clone().add(this.wallCheckDistance.clone().multiply(new Vec3(5, 0, 0)));
        let results = PhysicsSystem2D.instance.raycast(start, end, ERaycast2DType.Any, Physicsgroup.Player);
        return results.length > 0;
    }
    public damage(): void {
        this.fx.FlashFX();
        this.HitKnockBack();
    }
    async HitKnockBack() {
        this.isKnocked = true;
        this.rigidBody.linearVelocity = new Vec2(this.knockBackDirection.x * this.playerNode.getComponent(Player).facingDir, this.knockBackDirection.y);
        await delay(this.knockBackDuration);
        this.isKnocked = false;
    }
}


